<template>
	<div>
		<dv-loading v-if="loading">Loading...</dv-loading>
		<div ref="threejs"></div>
	</div>
</template>

<script>
	import * as THREE from 'three';
	import {
		GLTFLoader
	} from 'three/examples/jsm/loaders/GLTFLoader';
	import {
		OrbitControls
	} from "three/examples/jsm/controls/OrbitControls";
	import {
		TextGeometry
	} from "three/examples/jsm/geometries/TextGeometry";
	import {
		FontLoader
	} from "three/examples/jsm/loaders/FontLoader";
	import {
		CSS3DRenderer,
		CSS3DObject
	} from 'three/examples/jsm/renderers/CSS3DRenderer.js';
	import {
		h,
		createApp
	} from "vue";

	let laberDiv = null; //  DoM属性
	let scene = null;
	let camera = null;
	let renderer = null;
	let controls = null;
	let controls2 = null;
	let lanelRenderer = null
	let animationFrameId = null
	let model = null
	let that
	export default {
		props: {
			monitorType: {
				type: String,
				default: 'CEMS'
			}
		},
		name: 'ThreeDModel',
		data: function() {
			return {
				loading: false,
				_monitorType: "CEMS"
			};
		},
		mounted() {
			that = this;
			this.initThreeJS();
		},
		methods: {

			clearItem(index = 0) {
				if (index == scene.children.length) return
				let item = scene.children[index]
				if (item.isCSS3DObject) {
					scene.remove(item)

				}
				index += 1
			},

			itemClick(monitorType = 'CEMS') {
				that._monitorType = monitorType
				//console.log(scene.children)
				for (let i = 0; i <= 4; i++) {
					for (let item of scene.children) {
						console.log(item)
						if (item.isCSS3DObject) {
							scene.remove(item)
						}
					}
				}

				//scene.clear()
				// scene.remove(model)
				// scene.traverse((child) => {
				// 	if (child.material) {
				// 		child.material.dispose();
				// 	}
				// 	if (child.geometry) {
				// 		child.geometry.dispose();
				// 	}
				// 	child = null;
				// });
				// scene.clear()
				// //renderer.forceContextLoss()
				// model.traverse((obj) => {
				//     if (!obj.isMesh) return;
				//     obj.geometry.dispose();
				//     obj.material.dispose();
				// });
				// model = null;
				// renderer.dispose()
				// cancelAnimationFrame(animationFrameId);

				// scene = null
				// camera = null
				// renderer = null
				// controls = null
				// controls2 = null
				// lanelRenderer = null
				// animationFrameId = null
				// that.initThreeJS()
				that.getGasOnlineMonitorListByMonitorType()
				that.$forceUpdate()
			},

			getGasOnlineMonitorListByMonitorType() {
				//console.log(that._monitorType)
				that._monitorType = that._monitorType || 'CEMS'
				//console.log(that._monitorType)
				if (that._monitorType == 'CEMS' || that._monitorType == 'AIR_SITE' || that._monitorType == 'TSP') {
					that.ajax({
						url: 'onlineMonitor/getGasOnlineMonitorListByMonitorTypeV2',
						data: {
							monitorType: that._monitorType
						},
						contentType: 'application/x-www-form-urlencoded',
						success: function(res) {
							//that.dataList = res.data
							//console.log("在线监测设备", that.data9)
							if (res.data && res.data.length) that.createTag(res.data)
						}
					})
				} else if (that._monitorType == 'SHJ') {
					that.ajax({
						url: 'video/monitor/equipment/getListByEntId',
						data: {
							monitorType: that._monitorType
						},
						contentType: 'application/x-www-form-urlencoded',
						success: function(res) {
							//that.dataList = res.data
							//console.log("在线监测设备", that.data9)
							if (res.data && res.data.length) that.createTag2(res.data)
						}
					})
				} else {
					that.ajax({
						url: 'gasOutlet/warning/getWarningPositionList',
						data: {
							monitorType: that._monitorType
						},
						contentType: 'application/x-www-form-urlencoded',
						success: function(res) {
							//that.dataList = res.data
							//console.log("在线监测设备", that.data9)
							if (res.data && res.data.length) that.createTag2(res.data)
						}
					})
				}
			},

			createTag(dataList, index = 0) {
				if (index == dataList.length) return false
				let item = dataList[index]
				// 创建HTML元素并添加到场景中
				const div = document.createElement('div');
				div.className = 'label';
				div.style.transformStyle = 'preserve-3d'; // 重要！
				//div.innerHTML = item.monitorName || item.equipmentPosition; // 设置你的文本内容
				div.innerHTML = `<div>${item.monitorName || item.equipmentPosition}`
				if (item.pollutionMonitorList && item.pollutionMonitorList.length) {
					for (let item2 of item.pollutionMonitorList) {
						div.innerHTML +=
							`<div><span>${item2.pollutionName}</span><span style="margin-left:10px;">${item2.actualAmount || '--'}${item2.unitValue}</span></div>`
					}
					item.yCoords = item.yCoords + item.pollutionMonitorList.length * 0.2
				}

				div.innerHTML += '</div>'
				const element = new CSS3DObject(div);
				element.position.set(item.xCoords, item.yCoords, item.zCoords); // 设置元素在场景中的位置
				//element.position.set(-3, 0.3, 2); // 设置元素在场景中的位置
				element.scale.set(0.006, 0.006, 0.006)
				scene.add(element);

				if (item.yCoords >= 0.8) {
					const div2 = document.createElement('divImage');
					div2.className = 'labelImage';
					div2.style.transformStyle = 'preserve-3d'; // 重要！
					div2.style.height = '120px'

					if (item.pollutionMonitorList.length == 1) item.yCoords = item.yCoords - 0.6
					if (item.pollutionMonitorList.length == 3) item.yCoords = item.yCoords - 0.8

					//div2.style.height = 'preserve-3d'; // 重要！
					const element2 = new CSS3DObject(div2);
					element2.position.set(item.xCoords, item.yCoords, item.zCoords); // 设置元素在场景中的位置
					//element.position.set(-3, 0.3, 2); // 设置元素在场景中的位置
					element2.scale.set(0.006, 0.006, 0.006)
					scene.add(element2);
				}

				index += 1
				that.createTag(dataList, index)
			},

			createTag2(dataList, index = 0) {

				if (index == dataList.length) return false
				let item = dataList[index]
				// 创建HTML元素并添加到场景中
				const div = document.createElement('div');
				div.className = 'label';
				div.style.transformStyle = 'preserve-3d'; // 重要！
				div.innerHTML = item.monitorName || item.equipmentPosition; // 设置你的文本内容
				const element = new CSS3DObject(div);
				element.position.set(item.xCoords, item.yCoords, item.zCoords); // 设置元素在场景中的位置
				//element.position.set(-3, 0.3, 2); // 设置元素在场景中的位置
				element.scale.set(0.006, 0.006, 0.006)
				scene.add(element);

				const div2 = document.createElement('divImage');
				div2.className = 'labelImage';
				div2.style.transformStyle = 'preserve-3d'; // 重要！
				if (item.yCoords >= 0.8) {
					div2.style.height = '120px'
					item.yCoords = item.yCoords - 0.5
				} else if (item.yCoords > 0.3 && item.yCoords < 0.8) {
					div2.style.height = '90px'
					item.yCoords = item.yCoords - 0.4
				} else {
					div2.style.height = '50px'
					item.yCoords = item.yCoords - 0.3
				}
				//div2.style.height = 'preserve-3d'; // 重要！
				const element2 = new CSS3DObject(div2);
				element2.position.set(item.xCoords, item.yCoords, item.zCoords); // 设置元素在场景中的位置
				//element.position.set(-3, 0.3, 2); // 设置元素在场景中的位置
				element2.scale.set(0.006, 0.006, 0.006)
				scene.add(element2);

				index += 1
				that.createTag2(dataList, index)
			},


			initThreeJS() {
				that.loading = true
				const width = this.$refs.threejs.clientWidth;
				const height = this.$refs.threejs.clientHeight;

				// 创建场景、相机和渲染器
				scene = new THREE.Scene();
				camera = new THREE.PerspectiveCamera(75, width / height, 0.01, 600);
				renderer = new THREE.WebGLRenderer({
					antialias: true, // 开启抗锯齿
					alpha: true
				});
				renderer.shadowMap.enabled = true;

				renderer.setSize(width, height);
				this.$refs.threejs.appendChild(renderer.domElement);
				renderer.setClearAlpha(0); // 设置背景透明度为0
				renderer.domElement.style.background = 'transparent'; // 设置容器背景透明
				renderer.domElement.style.position = 'absolute'; // 确保容器是绝对定位，以便透明背景正常工作
				renderer.domElement.style.top = '0'; // 根据需要调整位置和大小
				renderer.domElement.style.left = '0'; // 根据需要调整位置和大小
				renderer.domElement.style.width = '100%'; // 根据需要调整位置和大小
				renderer.domElement.style.height = '100%'; // 根据需要调整位置和大小
				renderer.domElement.style.zIndex = '1'; // 确保在页面其他元素之下显示（如果需要）
				renderer.autoClear = false; // 不自动清除背景，以便可以设置透明背景色
				renderer.gammaInput = true;
				renderer.gammaOutput = true;
				renderer.setClearColor(0x000000, 0); // 设置背景颜色为黑色，但透明度为0（实际上不显示颜色）
				renderer.clear(); // 清除之前的任何渲染结果（如果有的话）
				renderer.setPixelRatio(window.devicePixelRatio); // 设置高清显示

				// 添加光源
				const ambientLight = new THREE.AmbientLight(0xFFF2D9, 1); // 环境光
				scene.add(ambientLight);
				const light = new THREE.DirectionalLight(0xEDF9FF, 2);
				light.position.set(-10, 16, 13);
				light.castShadow = true; // 启用阴影投射
				// 设置光源的阴影属性

				scene.add(light);

				// 加载3D模型
				const loader = new GLTFLoader();
				loader.load('https://demo-1254184403.cos.ap-chengdu.myqcloud.com/20250402.glb', (gltf) => {
					model = gltf.scene;
					model.traverse((obj) => {
						//console.log(obj)
						if (obj.isMesh) {
							obj.material.emissive = obj.material.color;
							obj.material.emissiveMap = obj.material.map;
						}
						if (obj.name.includes("平面")) {
							obj.receiveShadow = true
						} else {
							//if(obj.name.includes('底座'))obj.visible = false
							if (obj.castShadow !== undefined) {
								// 开启投射影响
								obj.castShadow = true;
							}
						}
					});

					model.scale.set(3, 3, 3);
					scene.add(model);
					model.rotation.x = 0; // 初始旋转角度
					model.rotation.y = 0; // 初始旋转角度
					model.rotation.z = 0; // 初始旋转角度

					camera.position.x = 0;
					camera.position.y = 3;
					camera.position.z = 5;
				}, (xh) => {
					let progress = (xh.loaded / xh.total).toFixed(2);
					if (Number(progress) == 1) {
						setTimeout(function() {
							that.loading = false
							that.$forceUpdate()
						}, 1000)
					}

					//console.log(progress)
					//console.log('loading', xh);
				}, (err) => {
					console.log('err', err)
				});

				lanelRenderer = new CSS3DRenderer();
				lanelRenderer.setSize(width, height);
				lanelRenderer.domElement.style.position = 'absolute';
				lanelRenderer.domElement.style.zIndex = '2';
				this.$refs.threejs.appendChild(lanelRenderer.domElement);

				// 添加鼠标控制旋转功能
				controls = new OrbitControls(camera, renderer.domElement);
				controls2 = new OrbitControls(camera, lanelRenderer.domElement);
				controls.enableDamping = true;
				controls.dampingFactor = 0.25;
				controls.screenSpacePanning = false;
				controls.minDistance = 10;
				controls.maxDistance = 500;

				controls2.enableDamping = true;
				controls2.dampingFactor = 0.25;
				controls2.screenSpacePanning = false;
				controls2.minDistance = 10;
				controls2.maxDistance = 500;
				//controls.maxPolarAngle = Math.PI / 2; // Prevents the camera from rotating upside-down (π/2 radians)
				// controls.addEventListener("change", () => {
				// 	renderer.render(scene, camera);
				// });
				window.addEventListener('resize', this.onWindowResize);

				this.animate();
				this.getGasOnlineMonitorListByMonitorType()
			},

			animate() {
				animationFrameId = requestAnimationFrame(this.animate);
				renderer.render(scene, camera);
				lanelRenderer.render(scene, camera);
				controls.update(); // required if controls.enableDamping = true, or if controls.autoRotate = true
			},

			onWindowResize(camera, renderer) {
				camera.aspect = window.innerWidth / window.innerHeight;
				//camera.updateProjectionMatrix();
				renderer.setSize(window.innerWidth, window.innerHeight);
				render();
			}

		}
	}
</script>

<style scoped>
	div {
		width: 100%;
		height: 100%;
		background: transparent;
		/* 根据需要调整大小 */
	}
</style>
<style>
	.label {
		padding: 10px;
		font-size: 22px;
		color: #fff;
		background: linear-gradient(0deg, rgba(4, 42, 128, 0.95), rgba(4, 42, 128, 0.75), rgba(4, 42, 128, 0.95));
		border-radius: 1px;
		border: 1px solid #75E7FF;
	}

	.labelImage {
		width: 30px;
		background-repeat: no-repeat;
		background-image: url('../assets/sIcon175.png');
		background-size: contain;
		background-size: 100% 100%;
	}
</style>